package com.qyhl.module_practice.team.detail;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.module_practice.activity.PracticeActFragment;
import com.qyhl.module_practice.substreet.trend.PracticeTrendFragment;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeTeamBean;
import com.qyhl.webtv.commonlib.service.NewsService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.weavey.loading.lib.LoadingLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_TEAM_DETAIL)
public class PracticeTeamDetailActivity extends BaseActivity implements PracticeTeamDetailContract.PracticeTeamDetailView {
    @BindView(R2.id.vol_num)
    TextView volNum;
    @BindView(R2.id.act_times)
    TextView actTimes;
    @BindView(R2.id.act_duration)
    TextView actDuration;
    @BindView(R2.id.score)
    TextView score;
    @BindView(R2.id.summary)
    TextView summary;
    @BindView(R2.id.introduction_layout)
    CardView introductionLayout;
    @BindView(R2.id.volunteer_list)
    TextView volunteerList;
    @BindView(R2.id.volunteer_list_layout)
    CardView volunteerListLayout;
    @BindView(R2.id.more)
    ImageView more;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.btn_error_back)
    ImageView btnErrorBack;
    @BindView(R2.id.bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R2.id.name)
    TextView name;
    @BindView(R2.id.title)
    TextView mTitle;
    @BindView(R2.id.appBar)
    AppBarLayout appBar;

    /**
     * 新闻服务
     */
    @Autowired(name = ServicePathConstant.NEWS_SERVICE)
    public NewsService newsService;


    private PracticeTeamDetailPresenter mPresenter;

    private String orgId;
    private String volId;
    private String instId;
    private String title;
    private boolean isMine;

    private enum CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    private CollapsingToolbarLayoutState state;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_team_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        orgId = getIntent().getStringExtra("orgId");
        if (StringUtils.isEmpty(orgId)) {
            orgId = "";
        }
        volId = getIntent().getStringExtra("volId");
        instId = getIntent().getStringExtra("instId");
        title = getIntent().getStringExtra("title");
        isMine = getIntent().getBooleanExtra("isMine", false);
        mPresenter = new PracticeTeamDetailPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        btnErrorBack.setVisibility(View.GONE);
        setSupportActionBar(toolbar);
        if (StringUtils.isEmpty(title)) {
            mTitle.setText("队伍详情");
        } else {
            mTitle.setText(title);
        }

        if (isMine) {
            more.setVisibility(View.VISIBLE);
        } else {
            more.setVisibility(View.GONE);
        }

        mPresenter.getDetail(orgId, volId);
    }

    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(orgId, volId);
            }
        });

        //折叠状态监听
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                    }
                } else {
                    if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                        state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                    }
                }
            }
        });

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(PracticeTeamBean bean) {
        btnErrorBack.setVisibility(View.GONE);
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        name.setText(bean.getName());
        volNum.setText(bean.getVolNums() + "");
        actTimes.setText(bean.getActNums() + "");
        actDuration.setText(DateUtils.PracticeServiceTimeFormat(bean.getActTimes()));
        score.setText(bean.getActScore() + "");

        if (StringUtils.isNotEmpty(bean.getDesc())) {
            introductionLayout.setVisibility(View.VISIBLE);
            summary.setText(bean.getDesc());
        } else {
            introductionLayout.setVisibility(View.GONE);
        }

        if (StringUtils.isNotEmpty(bean.getVolListName())) {
            volunteerListLayout.setVisibility(View.VISIBLE);
            volunteerList.setText(bean.getVolListName());
        } else {
            volunteerListLayout.setVisibility(View.GONE);
        }

        if (bean.getIsReview() == 0 && !volId.equals("0")) { //未在审核中
            if (bean.getUserOrgId() == bean.getId()) {
//                more.setVisibility(View.VISIBLE);
                bottomLayout.setVisibility(View.GONE);
            } else if (bean.getUserOrgId() == 0) {
//                more.setVisibility(View.INVISIBLE);
                bottomLayout.setVisibility(View.VISIBLE);
            } else {
//                more.setVisibility(View.INVISIBLE);
                bottomLayout.setVisibility(View.GONE);
            }
        } else {//审核中
//            more.setVisibility(View.INVISIBLE);
            bottomLayout.setVisibility(View.GONE);
        }


        List<String> nameList = new ArrayList<>();
        List<Fragment> fragments = new ArrayList<>();

        for (int i = 0; i < bean.getCatalogs().size(); i++) {
            nameList.add(bean.getCatalogs().get(i).getCatalogName());
            switch (bean.getCatalogs().get(i).getType()) {
                case 1:
                    fragments.add(newsService.getNewListFragment(bean.getCatalogs().get(i).getCatalogId()));
                    break;
                case 2:
                    break;
                case 3:
                    fragments.add(PracticeTrendFragment.newInstance(bean.getId() + "", true));
                    break;
                case 4:
                    fragments.add(PracticeActFragment.newInstance(orgId, 2, instId, ""));
                    break;
            }
        }

        viewPager.setAdapter(new Adapter(this.getSupportFragmentManager(), fragments, nameList));
        tabLayout.setViewPager(viewPager);
        tabLayout.getTitleView(0).getPaint().setFakeBoldText(true);

    }

    @Override
    public void setError(String msg) {
        btnErrorBack.setVisibility(View.VISIBLE);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void joinSuccess(String msg) {
        showToast(msg, 4);
        mPresenter.getDetail(orgId, volId);
        BusFactory.getBus().post(new Event.PracticeCenterRefresh(1));
    }

    @Override
    public void joinError(String msg) {
        showToast(msg, 4);
    }

    @Override
    public void exitSuccess(String msg) {
        showToast(msg, 4);
        mPresenter.getDetail(orgId, volId);
        BusFactory.getBus().post(new Event.PracticeCenterRefresh(1));
    }

    @Override
    public void exitError(String msg) {
        showToast(msg, 4);
    }

    @OnClick({R2.id.volunteer_list_layout, R2.id.more, R2.id.btn_error_back, R2.id.become_btn})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.volunteer_list_layout) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isVolunteer", true);
            bundle.putString("title", "志愿者");
            bundle.putString("orgId", orgId);
            RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER, bundle);

        } else if (id == R.id.more) {
            new OtherDialog.Builder(PracticeTeamDetailActivity.this)
                    .setContentView(R.layout.practice_dialog_team_exit)
                    .setCanceledOnTouchOutside(true)
                    .setWidth(1.0f)
                    .setGravity(Gravity.BOTTOM)
                    .setOnClickListener(R.id.exit_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPresenter.exitTeam(orgId, volId);
                        }
                    })
                    .setDismissButton(R.id.cancel_btn)
                    .show();
        } else if (id == R.id.btn_error_back) {
            finish();
        } else if (id == R.id.become_btn) {
            mPresenter.joinTeam(orgId, volId);
        }
    }


    class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> names;

        Adapter(FragmentManager fm, List<Fragment> fragmentList, List<String> names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names.get(position);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void collapsed() {
        if (state == CollapsingToolbarLayoutState.COLLAPSED) {
            appBar.setExpanded(true, true);
        }
    }

    public void expanded() {
        if (state == CollapsingToolbarLayoutState.EXPANDED) {
            appBar.setExpanded(false, true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_TEAM_DETAIL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_TEAM_DETAIL);
    }
}
